﻿using System.ComponentModel;

namespace LvcChong
{
    public partial class FormVehicleQuery : Form
    {
        private BindingList<VehicleInfoOutput> _source = new BindingList<VehicleInfoOutput>();
        private LayerHelper _layerHelper = new LayerHelper();

        public FormVehicleQuery()
        {
            InitializeComponent();
            pager.OnPageChanged += Pagination_OnPageChanged;
            pager.OnPageSizeChanged += Pager_OnPageSizeChanged;

            InitGridLayout();

            InitData();
        }

        private void Pager_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pager.Tag = null;
        }

        public FormVehicleQuery(string licNum, ValueType valueType) : this()
        {
            if (valueType == ValueType.LicenseNum) txtLicenseNum.Text = licNum;
            else if (valueType == ValueType.VIN) txtValue.Text = licNum;
            else if (valueType == ValueType.UserID) txtUserId.Text = licNum;
        }

        private void Pagination_OnPageChanged(object? sender, EventArgs e)
        {
            RefreshData();
        }

        private void InitGridLayout()
        {
            grid.InitializeRow += (s, e) =>
            {
                var item = e.Row.ListObject as VehicleInfoOutput;
                if (item == null) return;

                if (item.bindTime.ParseToLong(0) != 0)
                {
                    var time = item.bindTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(VehicleInfoOutput.bindTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
            };

            var displayCol = new List<UltraGridDisplayItem> {
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.userId), Caption="用户编号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.userName), Caption="用户名称", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.phone), Caption="手机号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.licenseNum), Caption="车牌号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.vehicleVinCode), Caption="VIN", Position=2,ColumnWidth =180},
                new UltraGridDisplayItem{ Key=nameof(VehicleInfoOutput.bindTime), Caption="绑定时间", Position=2,ColumnWidth =180},
            };

            grid.SetDataBinding(_source, null);
            UltraGridHelper.InitializeUltraGridDisplay(grid, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = true,
                EnableFilter = true,
            });

            grid.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            grid.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            grid.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);
        }

        private void InitData()
        {
            cboQueryType.SetDataSource(typeof(VehicleQueryType).EnumToNameValues(true), "Caption");
            cboQueryType.SelectedIndex = 2;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private async void RefreshData()
        {
            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.VehicleListQuery(new VehicleListInput
            {
                page = pager.CurrentPageNo,
                limit = pager.PageSize,
                fromPage = pager.CurrentPageNo - 1 <= 0 ? null : pager.CurrentPageNo - 1,
                leastTotal = pager.TotalRecords == 0 ? null : pager.TotalRecords,
                deepPageTokenArr = pager.Tag?.ToString(),
                queryType = cboQueryType.SelectedItem == null ? null : (int)((QueryType)cboQueryType.SelectedItem.DataValue),
                queryValue = txtValue.Text,
                userId = txtUserId.Text,
                licenseNum = txtLicenseNum.Text,
            }));
            _source.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pager.Tag == null)
                    pager.Tag = ret.OtherMap?.deepPageToken;
                else pager.Tag = pager.Tag + "," + ret.OtherMap?.deepPageToken;
                pager.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _source.Add(item);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            cboQueryType.SelectedIndex = 0;
            txtLicenseNum.Clear();
            txtValue.Clear();
            txtUserId.Clear();
        }

        private Task<T> LayerRefreshAsync<T>(Func<T> action)
        {
            var ret = Task.Run(() =>
            {
                try
                {
                    plQuery.UpdateUI(() => plQuery.Enabled = false);
                    _layerHelper.ShowOpaqueLayer(plGrid, 30);
                    return action();
                }
                finally
                {
                    _layerHelper.HideOpaqueLayer();
                    plQuery.UpdateUI(() => plQuery.Enabled = true);
                }
            });
            return ret;
        }
    }

    public enum ValueType
    {
        LicenseNum,
        VIN,
        UserID
    }
}